package com.maxjay.system.core.spring.security;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;
import org.springframework.stereotype.Component;

import com.maxjay.common.util.collection.CollectionUtil;
import com.maxjay.system.core.cache.SystemDataHolder;
import com.maxjay.system.model.Pair;

/**
 * 资源源数据定义，即定义某一URL资源可以被哪些角色访问
 * 
 * @author zhaixm
 */
@Component("urlSecurityMetadataSource")
public class UrlSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
	
	private UrlMatcher urlMatcher = new AntUrlPathMatcher();;

    // According to a URL, Find out permission configuration of this URL.
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		String url = ((FilterInvocation) object).getRequestUrl();
		List<Pair<String, Collection<ConfigAttribute>>> resourceAuthoritiesList = SystemDataHolder.getInstance().getResourceAuthoritiesList();
		if (CollectionUtil.isNotEmpty(resourceAuthoritiesList)) {
			Iterator<Pair<String, Collection<ConfigAttribute>>> ite = resourceAuthoritiesList.iterator();
			while (ite.hasNext()) {
				Pair<String, Collection<ConfigAttribute>> resourceAuthoritiesPair = ite.next();
				if (urlMatcher.pathMatchesUrl(resourceAuthoritiesPair.getFirst(), url)) {
					return resourceAuthoritiesPair.getSecond();
				}
			}
		}
		return null;
    }

    public boolean supports(Class<?> clazz) {
        return true;
    }
    
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

}
